package com.waymap.utils;

import com.waymap.domain.LotNumber;
import com.waymap.mapper.LotNumberMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

@Component
public class NewNo {

    @Resource
    private LotNumberMapper lotNumberMapper;
    public  String getNewNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateNowStr = sdf.format(new Date());
        String newLotNumberNo = "000";
        Optional<LotNumber> lotNumber = Optional.ofNullable(lotNumberMapper.selectOne(new LotNumber()));
        if(lotNumber.isPresent()){
            LotNumber lot = lotNumber.get();
            //判断是否为同一天
            boolean sameDay = DateUtil.isSameDay(lot.getCurrentDate(), new Date());
            LotNumber lotNum = new LotNumber();
            if(sameDay){
                //如果日期相同 累加
                if (lot.getNo()>=0) {
                    int no = lot.getNo() + 1;
                    newLotNumberNo = String.format(dateNowStr + "%03d", no);
                }
                lotNum.setId(lot.getId());
                lotNum.setCurrentDate(new Date());
                lotNum.setLotNumber(newLotNumberNo);
                lotNum.setNo(lot.getNo()+1);
                lotNumberMapper.updateByPrimaryKey(lotNum) ;
            }else {
                //如果日期不相同 从0开始
                newLotNumberNo = String.format(dateNowStr + "%03d", 1);
                lotNum.setId(lot.getId());
                lotNum.setCurrentDate(new Date());
                lotNum.setLotNumber(newLotNumberNo);
                lotNum.setNo(1);
            }
            lotNumberMapper.updateByPrimaryKey(lotNum) ;
        }else {
            //数据库无数据，保存当前数据
            newLotNumberNo = String.format(dateNowStr + "%03d", 1);
            LotNumber lotNum = new LotNumber();
            lotNum.setCurrentDate(new Date());
            lotNum.setLotNumber(newLotNumberNo);
            lotNum.setNo(1);
            lotNumberMapper.insert(lotNum);
        }
        return newLotNumberNo;

    }
}
